﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;
using ePlanet.ArchiveMange.Services;
using DreamBuilder.Core.Container;
using ePlanet.ArchiveMange.Models;
using Microsoft.Practices.Unity;
using Web.SystemConfig.Services;
using ePlanet.SingleWell.Services;
using CommonModule;
using ePlanet.SingleWell.Models;
using Web.SystemConfig.WorkFlow;

namespace Web.Views.ArchiveView
{
    public partial class AccountView : ArchiveFlowEditPageBase
    {
        #region 属性变量
        [Dependency]
        public ICodeTable CodeTableService
        {
            get;
            set;
        }

        [Dependency]
        public IArchiveMenuService ArchiveMenuService
        {
            get;
            set;
        }

        [Dependency]
        public IPageFileService PageFileService
        {
            get;
            set;
        }

        [Dependency]
        public IAuth_Org orgService
        {
            get;
            set;
        }

        public string archiveTypeName;
        /// <summary>
        /// 档案类型
        /// </summary>
        public string ReqArchiveType
        {
            get
            {
                if (this.Request.QueryString["archiveType"] != null)
                {
                    return this.Request.QueryString["archiveType"];
                }
                else
                {
                    throw new Exception("档案类型不能为空");
                }
            }
        }

        public string ArchiveID
        {
            get
            {
                if (Request.QueryString["archiveId"] != null)
                {
                    ViewState["archiveId"] = Request.QueryString["archiveId"];
                }
                if (ViewState["archiveId"] != null)
                {
                    return ViewState["archiveId"].ToString();
                }
                else
                {
                    ViewState["archiveId"] = Guid.NewGuid().ToString();
                    return ViewState["archiveId"].ToString();
                }
            }
        }

        #endregion

        #region 页面初始化
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                
                //this.attachArchive.ObjectID = ArchiveID;
                //this.attachArchive.ObjectTableName = "";
                //AddAttachmentInfos();
                InitControls();
                LoadHidden();
                LoadData();
                LoadArchivePageFile();
                //LoadApproveData();

                AddAttacheGrid();
                
            }
        }

        /// <summary>
        /// 初始化数据项
        /// </summary>
        private void InitControls()
        {

            //保密期限
            DataSet keepSecurityTime = CodeTableService.GetCodeTableDataByType("KeepSecurityTime");
            if (keepSecurityTime != null && keepSecurityTime.Tables.Count > 0)
            {
                this.ddlKeepSecurityTime.DataSource = keepSecurityTime;
                this.ddlKeepSecurityTime.DataTextField = "Code_Desc";
                this.ddlKeepSecurityTime.DataValueField = "CodeTableID";
                this.ddlKeepSecurityTime.DataBind();
                this.ddlKeepSecurityTime.Items.Insert(0, new ListItem("--请选择--", "-1"));
            }

            DataSet KeepTime = CodeTableService.GetCodeTableDataByType("KeepTime");
            if (KeepTime != null && KeepTime.Tables.Count > 0)
            {
                this.ddlKeepTime.DataSource = KeepTime;
                this.ddlKeepTime.DataTextField = "Code_Desc";
                this.ddlKeepTime.DataValueField = "CodeTableID";
                this.ddlKeepTime.DataBind();
                this.ddlKeepTime.Items.Insert(0, new ListItem("--请选择--", "-1"));
            }
            DataSet CarrierType = CodeTableService.GetCodeTableDataByType("CarrierType");
            if (CarrierType != null && CarrierType.Tables.Count > 0)
            {
                this.ddlCarrierType.DataSource = CarrierType;
                this.ddlCarrierType.DataTextField = "Code_Desc";
                this.ddlCarrierType.DataValueField = "CodeTableID";
                this.ddlCarrierType.DataBind();
                this.ddlCarrierType.Items.Insert(0, new ListItem("--请选择--", "-1"));
            }

            DataSet SecurityData = CodeTableService.GetCodeTableDataByType("SecurityType");
            if (CarrierType != null && CarrierType.Tables.Count > 0)
            {
                this.ddlSecurity.DataSource = SecurityData;
                this.ddlSecurity.DataTextField = "Code_Desc";
                this.ddlSecurity.DataValueField = "CodeTableID";
                this.ddlSecurity.DataBind();
                this.ddlSecurity.Items.Insert(0, new ListItem("--请选择--", "-1"));
            }

            DataSet AccountTypeData = CodeTableService.GetCodeTableDataByType("AccountType");
            if (AccountTypeData != null && AccountTypeData.Tables.Count > 0)
            {
                this.ddlAccountType.DataSource = AccountTypeData;
                this.ddlAccountType.DataTextField = "Code_Desc";
                this.ddlAccountType.DataValueField = "CodeTableID";
                this.ddlAccountType.DataBind();
                this.ddlAccountType.Items.Insert(0, new ListItem("--请选择--", "-1"));
            }

            //int year = DateTime.Now.Year;
            //for (int i = year - 10; i < year + 10; i++)
            //{
            //    this.ddlYear.Items.Add(new ListItem("--" + i + "--", i.ToString()));
            //}
            //this.ddlYear.Items.Insert(0, new ListItem("--请选择--", "-1"));

            ArchiveMangeModal.ARCHIVEMENUDataTable dtArchiveMenu = ArchiveMenuService.GetArchiveMenuById(ReqArchiveType);
            if (dtArchiveMenu != null && dtArchiveMenu.Rows.Count > 0)
            {
                this.txtArchiveType.Text = (dtArchiveMenu.Rows[0] as ArchiveMangeModal.ARCHIVEMENURow).TYPECODE;
                this.archiveTypeName = (dtArchiveMenu.Rows[0] as ArchiveMangeModal.ARCHIVEMENURow).ARCHIVEMENU;
            }
            //来源
            this.txtArchiveSource.Text = "在线录入__档案整理";
            this.txtFileOrgName.Text = "厂中心档案室";
            this.txtBoxNum.Text = "未装盒";
            this.h_FileOrgID.Value = CommonUtil.GetConfigValue("ArchiveManage", "DefalutApproveOrgID");

            this.txtArchiveNum.Enabled = false;
            this.txtArchiveSource.Enabled = false;
            this.txtFullFondsNum.Enabled = false;
            this.txtArchiveType.Enabled = false;

            this.h_ArchiveTypeId.Value = ReqArchiveType;

            //如果类别是会计02，会计03，会计04，则隐藏会计凭证行 [起凭证号，止凭证号，凭证类别]
            if (ReqArchiveType != ((int)ArchiveTableEnum.AccountI01).ToString())
            {
                this.trAccount.Visible = false;
            }
        }

        private void LoadHidden()
        {
            h_arcvhive.Value = ArchiveID;
            h_archiveType.Value = ReqArchiveType;
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        private void LoadData()
        {
            IAccountArchiveService DocumentArchiveService = UContainer.Resolve<IAccountArchiveService>();
            ArchiveMangeModal.ACCOUNT_VOUCHER_ARCHIVEDataTable dt = DocumentArchiveService.GetAllDocumenArchivetDataById(ArchiveID);
            if (dt.Rows.Count > 0)
            {
                this.CurrentPageState = PageState.State_Edit;
                ArchiveMangeModal.ACCOUNT_VOUCHER_ARCHIVERow row = dt.Rows[0] as ArchiveMangeModal.ACCOUNT_VOUCHER_ARCHIVERow;
                this.txtArchiveNum.Text = row.ARCHIVENUM;
                this.txtArchiveSource.Text = row.ARCHIVESOURCE;
                ArchiveMangeModal.ARCHIVEMENUDataTable dtMenu = ArchiveMenuService.GetArchiveMenuById(row.ARCHIVETYPE.ToString());
                ArchiveMangeModal.ARCHIVEMENURow drMenu = dtMenu.Rows[0] as ArchiveMangeModal.ARCHIVEMENURow;
                this.txtArchiveType.Text = drMenu.ARCHIVEMENU;
                this.h_ArchiveTypeId.Value = row.ARCHIVETYPE.ToString();
                this.txtBoxNum.Text = row.BOXNUM;
                this.txtEndAccount.Text = row.ENDACCOUNT;
                this.txtEndTime.Text = row.ENDTIME.ToString("yyyy-MM-dd");
                //DataTable dtOrg = orgService.GetORGInfo(row.FILEORGID);
                //this.txtFileOrgName.Text = dtOrg.Rows[0]["Org_Name"].ToString();
                //this.h_FileOrgID.Value = row.FILEORGID;
                this.txtFileOrgName.Text = row.FILEORGID;
                this.txtFullFondsNum.Text = row.FULLFONDSNUM;
                this.txtMainBodyNum.Text = row.IsMAINBODYNUMNull()?string.Empty: row.MAINBODYNUM.ToString();
                this.txtPageNum.Text = row.IsPAGENUMNull()?string.Empty: row.PAGENUM.ToString();
                this.txtFileNum.Text = row.IsPAGEFILENUMNull()?string.Empty: row.PAGEFILENUM.ToString();
                this.txtStartAccount.Text = row.STARTACCOUNT;
                this.txtStartTime.Text = row.STARTTIME.ToString("yyyy-MM-dd");
                this.txtStorageType.Text = row.IsSTORAGETYPENull() ? string.Empty : row.STORAGETYPE;
                this.txtSummary.Text = row.SUMMARY;
                this.txtTempOrderNum.Text = row.TEMPORDERNUM;
                this.txtTitle.Text = row.TITLE;
                this.ddlYear.Text = row.IsK_YEARNull()?"": row.K_YEAR.ToString();
                this.ddlAccountType.SelectedValue = row.ACCOUNTTYPE;
                this.ddlCarrierType.SelectedValue = row.F_CARRIERTYPE;
                this.ddlKeepTime.SelectedValue = row.F_KEEPTIME;
                this.ddlSecurity.SelectedValue = row.F_SECURITYTYPE;
                this.ddlKeepSecurityTime.SelectedValue = row.F_KEEPSECURITYTIME;
            }
        }

        /// <summary>
        /// 加载卷内件
        /// </summary>
        private void LoadArchivePageFile()
        {
            //加载刚编辑好的卷内件
            DataTable dtPageFile = null;
            IList<string> list = new
            List<string>();
            List<string> HasList = null;
            //卷内件数据
            if (Session["ArchivePageFile"] != null)
            {
                Hashtable ht = (Hashtable)Session["ArchivePageFile"];
                if (ViewState["HasFileList"] != null)
                {
                    HasList = (List<string>)ViewState["HasFileList"];
                }
                else
                {
                    HasList = new List<string>();
                }
                //Key是PageFileId，Value是ArchiveType
                foreach (string key in ht.Keys)
                {
                    if (ht[key].ToString() == ReqArchiveType) //找出包含此类型的卷内件ID
                    {
                        if (!HasList.Contains(key))  //判断空卷内件是否已经加入列表,没加入的加入列
                        {
                            //加入已经加入的列表
                            HasList.Add(key);
                        }
                    }
                }
                dtPageFile = PageFileService.GetPageFileByFileIdList(HasList);
                Session.Remove("ArchivePageFile");
                ViewState["HasFileList"] = HasList;//更新视图状态
            }
            //加载已经有的卷内件
            IAccountArchiveService acount = UContainer.Resolve<IAccountArchiveService>();
            DataTable dt2 = acount.GetPageFileByDATAID(ArchiveID);
            if (dtPageFile != null)
            {
                dtPageFile.Merge(dt2);
            }
            else
            {
                dtPageFile = dt2;
            }
            dtPageFile.TableName = "pagefile";
            this.gv_PageFileView.DataSource = dtPageFile;
            this.gv_PageFileView.DataBind();

        }

        /// <summary>
        /// 加载审核信息
        /// </summary>
        private void LoadApproveData()
        {

        }

        /// <summary>
        /// 附件实体增加更多信息
        /// </summary>
        private void AddAttachmentInfos()
        {
            Hashtable addInfos = new Hashtable();
            addInfos.Add("FunctionID", "0"); //功能ID(1：发文文档 2：发文附件 3：收文文档 4：收文附件 5：即时消息附件 6：新闻附件)
            addInfos.Add("FileTypeID", ""); //附件文件夹类型
            addInfos.Add("FileURL", ""); //附件存储路径
            addInfos.Add("IsXml", "0"); //是否XML代码化
            addInfos.Add("CreateUserID", this.CurrentUser.User_ID); //用户ID 目前可以写个固定的值作为测试
            addInfos.Add("Remark", "即时消息附件"); //备注
            if (Session["AddInfos"] == null)
            {
                Session.Add("AddInfos", addInfos);
            }
            else
            {
                Session.Remove("AddInfos");
                Session.Add("AddInfos", addInfos);
            }
        }

        private void AddAttacheGrid()
        {
            this.gv_Attach.DataSource = GetAttachData();
            this.gv_Attach.DataBind();
        }
        /// <summary>
        /// 获取附件信息
        /// </summary>
        /// <returns></returns>
        private DataTable GetAttachData()
        {
            DataTable rtnDataTable = null;


            IAttachmentService oIAttachmentService = UContainer.Resolve<IAttachmentService>();
            oIAttachmentService.Initialize(AttachDbHelperString.AccountFile);
            List<AttachmentModel> attachments = oIAttachmentService.GetAttachmentModelByObjectID(ArchiveID);

            if (attachments != null && attachments.Count > 0)
            {
                rtnDataTable = new DataTable();
                rtnDataTable.Columns.Add("attachmentid");
                rtnDataTable.Columns.Add("AttachmentName");
                rtnDataTable.Columns.Add("UpdateTime");
                rtnDataTable.Columns.Add("AttachmentSize");
                rtnDataTable.Columns.Add("DBHelperString");
                rtnDataTable.Columns.Add("uploadtime");

                foreach (AttachmentModel model in attachments)
                {
                    DataRow newRow = rtnDataTable.NewRow();
                    newRow["attachmentid"] = model.AttachmentID;
                    newRow["AttachmentName"] = model.AttachmentName;
                    newRow["UpdateTime"] = model.UpdateTime.ToShortDateString();
                    newRow["AttachmentSize"] = (model.AttachmentSize / ((float)1024)).ToString() + "M";
                    newRow["uploadtime"] = model.UpdateTime.ToShortDateString();
                    newRow["DBHelperString"] = AttachDbHelperString.AccountFile;

                    rtnDataTable.Rows.Add(newRow);
                }
            }

            return rtnDataTable;
        }
        #endregion

        #region 页面事件
        protected void gv_PageFileView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRowView drv = (DataRowView)e.Row.DataItem;
                System.Web.UI.WebControls.GridViewRow rows = ((GridViewRow)e.Row);
                string DataID = drv["DataID"].ToString();
                //int orderNum = Convert.ToInt32(drv["ORDERNUM"]);
                string url = "ViewPageFile.aspx?archiveId=" + ArchiveID + "&archiveType=" + ReqArchiveType + "&DataID=" + DataID +"&op=" + OP.ToLower();
                
                ((System.Web.UI.WebControls.Button)rows.FindControl("view")).Attributes["onclick"] = "javascript:openViewPage('" + url + "');return false;";
                ((System.Web.UI.WebControls.HyperLink)rows.FindControl("down")).Attributes["onclick"] = "javascript:ChangeOrder('" + DataID + "','down');";
                e.Row.Cells[6].Text = CodeTableService.GetpkNameByCodepkValue(drv["F_SECURITYTYPE"].ToString());
                e.Row.Cells[7].Text = CodeTableService.GetpkNameByCodepkValue(drv["F_KEEPTIME"].ToString());
                //e.Row.Cells[8].Text = orgService.GetOrgNameByOrgID(drv["FIleOrgID"].ToString());
                e.Row.Cells[10].Text = CodeTableService.GetpkNameByCodepkValue(drv["F_CARRIERTYPE"].ToString());
            }
        }

        #endregion
    }
}